package com.rayson.yututu.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rayson.yututu.annotation.AuthCheck;
import com.rayson.yututu.common.BaseResponse;
import com.rayson.yututu.constant.UserConstant;
import com.rayson.yututu.exception.ErrorCodeEnum;
import com.rayson.yututu.exception.ThrowUtils;
import com.rayson.yututu.manager.auth.SpaceUserAuthManager;
import com.rayson.yututu.manager.auth.StpKit;
import com.rayson.yututu.manager.auth.annotation.SaSpaceCheckPermission;
import com.rayson.yututu.manager.auth.model.SpaceUserPermissionConstant;
import com.rayson.yututu.model.entity.Picture;
import com.rayson.yututu.model.entity.Space;
import com.rayson.yututu.model.entity.User;
import com.rayson.yututu.model.enums.PictureReviewStatusEnum;
import com.rayson.yututu.model.req.picture.*;
import com.rayson.yututu.model.vo.PictureVO;
import com.rayson.yututu.model.vo.TagCategoryVO;
import com.rayson.yututu.service.PictureService;
import com.rayson.yututu.service.SpaceService;
import com.rayson.yututu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Objects;

/**
 * Author: rayson
 * Description:
 * Version: 1.0
 * Date: 2024-12-24 21:00
 */
@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;


    @PostMapping("/upload")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> upload(MultipartFile file,
                                          PictureUploadReq pictureUploadReq,
                                          HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return BaseResponse.success(pictureService.uploadPicture(file, pictureUploadReq, loginUser));
    }

    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(@RequestBody PictureUploadReq pictureUploadReq,
                                                      HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return BaseResponse.success(pictureService.uploadPicture(null, pictureUploadReq, loginUser));
    }

    // 根据id删除图片：管理员和本人都可以删除
    @DeleteMapping("/{id}")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Void> deletePictureById(@PathVariable("id") String id, HttpServletRequest request) {
        pictureService.deletePictureById(id, request);
        return BaseResponse.success(null, "删除成功");
    }

    // 更新图片
    @PostMapping("/update")
    public BaseResponse<Void> updatePicture(@RequestBody PictureUpdateReq pictureUpdateReq) {
        pictureService.updatePicture(pictureUpdateReq);
        return BaseResponse.success(null, "更新成功");
    }

    // 根据id获取图片，管理员用，不脱敏
    @GetMapping("/admin/{id}")
    public BaseResponse<Picture> getPictureById(@PathVariable("id") String id) {
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(Objects.isNull(picture), ErrorCodeEnum.PARAM_ERROR, "图片不存在");
        return BaseResponse.success(picture);
    }

    // 根据id获取图片，普通用户用，脱敏
    @GetMapping("/{id}")
    public BaseResponse<PictureVO> getPictureVOById(@PathVariable("id") String id, HttpServletRequest request) {
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(Objects.isNull(picture) ||
                        (!PictureReviewStatusEnum.PASS.getStatus().equals(picture.getReviewStatus())
                                && StrUtil.isBlank(picture.getSpaceId())),
                ErrorCodeEnum.PARAM_ERROR, "图片不存在");
        String spaceId = picture.getSpaceId();
        Space space = null;
        if (StrUtil.isNotBlank(spaceId)) {
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCodeEnum.NO_AUTH, "没有权限查看图片");
            space = spaceService.getById(spaceId);
        }
        PictureVO pictureVO = PictureVO.toPictureVO(picture);
        User user = userService.getById(picture.getUserId());
        pictureVO.setUserVO(user.toUserVO());
        pictureVO.setPermissionList(spaceUserAuthManager.getPermissionList(space, userService.getLoginUser(request)));
        return BaseResponse.success(pictureVO);
    }

    // 分页图片列表：管理员
    @GetMapping("/admin/list")
    public BaseResponse<Page<Picture>> listPicture(PictureQueryReq queryReq) {
        return BaseResponse.success(pictureService.listPicture(queryReq));
    }

    @GetMapping("/tagCategory")
    public BaseResponse<TagCategoryVO> getTagCategory() {
        return BaseResponse.success(pictureService.getTagCategory());
    }

    // 分页图片列表：普通用户
    @GetMapping("/list")
    public BaseResponse<Page<PictureVO>> listPictureVO(PictureQueryReq queryReq) {
        return BaseResponse.success(pictureService.listPictureVO(queryReq));
    }

    @PostMapping("/admin/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Void> reviewPicture(@RequestBody @Valid PictureReviewReq pictureReviewReq, HttpServletRequest request) {
        pictureService.reviewPicture(pictureReviewReq, request);
        return BaseResponse.success(null, "操作成功");
    }

    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> getPictureFromInternet(@RequestBody @Valid PictureBatchReq pictureBatchReq,
                                                        HttpServletRequest request) {
        Integer count = pictureService.getPictureFromInternet(pictureBatchReq, userService.getLoginUser(request));
        return BaseResponse.success(count, "图片抓取成功");
    }

    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Void> batchEditPicture(@RequestBody @Valid BatchEditPictureReq batchEditPictureReq,
                                               HttpServletRequest request) {
        pictureService.batchEditPicture(batchEditPictureReq, userService.getLoginUser(request));
        return BaseResponse.success(null, "批量编辑成功");
    }

}
